package com.py.credit.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.ClientAnchor;
import org.apache.poi.ss.usermodel.Comment;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Drawing;
import org.apache.poi.ss.usermodel.RichTextString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.TableResult;
import com.py.credit.service.DataEntryService;
import com.py.credit.service.ErrorDataService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.utils.DateUtil;
import com.py.credit.utils.ExcelUtil;
import com.py.framework.core.common.Page;
import com.py.framework.core.helper.HttpServletHelper;

@RestController
@RequestMapping(value = "/errorData")
public class ErrorDataController {
	
	@Autowired
	private ErrorDataService errorDataService;
	
	@Autowired
	private RemoteBaseService remoteBaseService;
	/**
	 * 
	　　* @Title: exportErrorData   
	　　* @Description: TODO(问题数据批量导出excel处理)   
	　　* @param  request
	　　* @param  tableId  
	　　* @param  contentId	版本ID
	　　* @param  startTime	采集开始时间
	　　* @param  endTime	采集结束时间
	　　* @param  page
	　　* @param  response
	　　* @return    设定文件   
	　　* @return RestServiceResult<Object>    返回类型   
	　　* @throws   
	　　
	 */
	
	@RequestMapping(value = "/exportErrorData.json")
	public RestServiceResult<Object> exportErrorData(HttpServletRequest request,
			@RequestParam(value = "tableId", defaultValue = "", required = true) Integer tableId,
			@RequestParam(value = "deptId", defaultValue = "", required = true) Integer deptId,
			@RequestParam(value = "startTime", defaultValue = "", required = true) String startTime,
			@RequestParam(value = "endTime", defaultValue = "", required = true) String endTime, Page page, HttpServletResponse response) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("ErrorDataProcessingController#exportErrorData", "未获取到当前用户信息！");
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			 return result;
		}
		try {
			//获取当前使用的版本ID
			Integer contentId = errorDataService.getcontentId();
			//异常处理数据
			List<Map<String, Object>> data = errorDataService.getTableListForPage(tableId, startTime, endTime, page,
					userInfo,deptId);						
				// 获取顶级部门ID
				Long topDeptId = userInfo.getOfficeId();
				String pIds = userInfo.getAllParentId();
				if (StringUtils.isNotBlank(pIds)) {
					String t = StringUtils.split(pIds, ",")[0];
					topDeptId = StringUtils.isNoneBlank(t) ? Long.valueOf(t) : topDeptId;
				}
				String fileName = "";
				String tipId = tableId + "_" + topDeptId;
				// 根据tableId获取excel标题,双公示的特殊处理		
				TableResult table = errorDataService.getTableColumns(tableId, contentId, tipId);	
				if(table==null) {
					result.setCode(RestServiceResult.CODE_UNKNOW);
					result.setMsg("当前目录版本未获取到对应表单信息，请联系管理员分配！");
					return result;
				}else {
				downloadErrordata(response, table,data);
				//原有数据的record_id
				List<String> list = new ArrayList<>();
				List<String> batchIds = new ArrayList<>();
				if(!data.isEmpty()) {
					for(Map<String, Object> error:data) {
						list.add(String.valueOf(error.get("record_id")));
						batchIds.add( String.valueOf(error.get("batch_Id")));
					}	
				//	删除数据库原有数据，并减去总数和错误数 ; 异常数据处理时错误减正确加
					errorDataService.deleteErrorData(tableId,list,batchIds);
				}
				
			
				}	
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("异常数据导出处理异常，请稍后再试！");
			ExceptionLogger.error("ErrorDataController#exportErrorData", "异常数据导出处理异常！ERROR:" + e.getMessage(),
					e);

		}
		 return result;
	}
	
	public static void downloadErrordata(HttpServletResponse response, TableResult table,List<Map<String, Object>> data) throws Exception {
		response.setContentType("application/vnd.ms-excel");
		HSSFWorkbook workbook = null;
		OutputStream fOut = null;
		
		
		// 产生工作簿对象
		workbook = new HSSFWorkbook();
		// 产生工作表对象
		HSSFSheet sheet = workbook.createSheet();
		// 得到一个poi工具
		CreationHelper factory = workbook.getCreationHelper();
		// 得到换图对象
		Drawing drawing = sheet.createDrawingPatriarch();
		// 设置注释位置
		ClientAnchor anchor = factory.createClientAnchor();
		workbook.setSheetName(0, "异常数据");
		HSSFRow row = null;
		HSSFCell cell = null;

		// 进行转码，使其支持中文文件名
		String fileNanme = URLEncoder.encode(table.getTableNameCN(), "UTF-8");
		response.setHeader("content-disposition", "attachment;filename=" + fileNanme + ".xls");
		// 创建标题行
		row = sheet.createRow(0);
		//标题行的英文名和对应下标创建一个map
		Map<String,Integer> titlemap = new HashMap<String,Integer>();
		Map<String,String> type = new HashMap<String,String>();
		if (!CollectionUtils.isEmpty(table.getColumns())) {
		
			for (int i = 0; i < table.getColumns().size(); i++) {
				sheet.setColumnWidth(i, 8000);
				cell = row.createCell(i+1);
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue(table.getColumns().get(i).getMetricName());
				Comment comment = drawing.createCellComment(anchor);
				RichTextString str = factory.createRichTextString(table.getColumns().get(i).getTips());
				comment.setString(str);
				cell.setCellComment(comment);
				titlemap.put(table.getColumns().get(i).getMetricCode(), i+1);
				type.put(table.getColumns().get(i).getMetricCode(),table.getColumns().get(i).getFieldType());
			}
			cell=row.createCell(0);
			cell.setCellType(HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue("异常原因");
			titlemap.put("typeMsgReason", 0);
			type.put("typeMsgReason", "varchar");
		}		
			//写入数据	
			for (int j = 0; j < data.size(); j++) {
				row = sheet.createRow(j + 1);// 创建一行
				//根据map的key和titlemap的key相等进行对应的列赋值
				for(Entry<String, Integer> s : titlemap.entrySet()) {
					cell=row.createCell(s.getValue());
					try {
						if(type.get(s.getKey()).equals("timestamp")||type.get(s.getKey()).equals("datetime")&&type.get(s.getKey()).lastIndexOf(".") != -1) {
							cell.setCellValue( DateUtil.getInstance().parseDateStr(data.get(j).get(s.getKey()).toString(), "yyyy-MM-dd"));
						}else {
							cell.setCellType(HSSFCell.CELL_TYPE_STRING);
							cell.setCellValue(data.get(j).get(s.getKey()).toString());
						}
					}catch (Exception e) {
						ExceptionLogger.error("ErrorDataController#exportErrorData", "异常数据导出处理异常！ERROR字段 :"+s.getKey() + e.getMessage(),
								e);
					}
				
					
				}
		}
		fOut = response.getOutputStream();
		workbook.write(fOut);
		workbook.close();
		fOut.flush();
		fOut.close();
	}
}
